import axios from 'axios';
import { Message, Loading } from 'element-ui';

const instance = axios.create({
    timeout: 15000,
    baseURL: 'http://120.24.64.5:8088/'
});
let loading = null;
let count = 0;

instance.interceptors.request.use(config => {
    if (count == 0) {
        loading = Loading.service({
            
        })
    }

    count++;
    const token = localStorage.getItem('token');
    if (token) {
        config.headers = config.headers || {};
        config.headers['Authorization'] = token;
    }
    return config;
}, err => {
    return Promise.reject(err);
})

instance.interceptors.response.use(res => {
    count--;
    if (count == 0) {
        loading.close();
    }
    if (res.data.errno === 0){
        return res.data;
    }
    if (res.data.code !== 200) {
        Message.error(res.data.message)
        if (res.data.code === 401) {
            localStorage.clear();
            location.reload();
        }
    }
    return res.data;
}, err => {
    return Promise.reject(err);
})

export default instance;